<template>
  <div class="contentBox setScrollbar">
    <div class="fixed">
      <el-button size="mini" @click="goback">返回</el-button>
    </div>
    <div class="detail">
      <h2>{{ detail.discussTitle }}</h2>
      <div class="detailInfo">
        <div class="info_left share">
          <span>日期：</span>
          <span>{{ detail.creatDate }}</span>
        </div>
        <div class="info_right share">
          <span>{{ detail.classification }}</span>
          <span>类别：</span>
        </div>
      </div>
      <div class="detailConten detailShare setScrollbar">{{ detail.discussContent }}</div>
      <div class="interactive">
        <div>附件：</div>
        <div class="interactive_left" v-if="detail.fileList&&detail.fileList.length>0">
          <a
            href="javascript:void(0)"
            v-for="(item,index) in detail.fileList"
            :key="item.file_path"
            target="_self"
            @click="download(item.file_id)"
          >{{index+1}}.{{item.file_name}}</a>
        </div>
        <div style="text-align:left;flex:1;font-size:14px" v-else>暂无附件</div>
        <div class="thumbs_up">
          <span v-show="!thumbsUpFlag" class="iconfont icon-dianzan" @click="throttleThumbsUpShow" />
          <span
            v-show="thumbsUpFlag"
            class="iconfont icon-dianzan red"
            @click="throttleThumbsUpShow"
          />
          <i>{{ detail.spotNum }}</i>
        </div>
        <!-- <div class="collection"> 收藏
          <span v-show="!collectionFlag" class="iconfont icon-shoucang5" @click="collectionShow"></span>
          <span v-show="collectionFlag" class="iconfont icon-shoucang5 red" @click="collectionShow"></span>
          <i>{{collectionNum}}</i>
        </div>-->
      </div>
      <div :style="{visibility:visibility}">
        <div class="userInfo">
          <div class="head">
            <span class="el-icon-s-custom"></span>
            <!-- <img src="" alt=""> 如果有用户头像 -->
          </div>
          <span>{{name}}</span>
        </div>
        <el-input
          type="textarea"
          class="setHeight"
          v-model="commentText"
          maxlength="2000"
          placeholder="欢迎评论"
          @keyup.ctrl.enter.native="commenthandle"
        />
        <div class="commentBtn">
          <div class="commentInfo">
            <span>Ctrl + Enter 发表</span>
            <span>{{commentText.length}}/2000字</span>
          </div>
          <el-button type="primary" :loading="commentLoading" @click="commenthandle">评论</el-button>
        </div>
      </div>
      <div style="height:18px; margin-bottom:10px" :style="{visibility:visibility}">
        <div class="comment_total">
          <span>共</span>
          <span>{{ total }}</span>
          <span>条</span>
        </div>
      </div>
      <div class="comment detailShare setScrollbar" :style="{visibility:visibility}">
        <div v-if="commentFlag">
          <ul>
            <li v-for="(item,index) in list" :key="index">
              <div class="comment_content">
                <div class="comment_user">
                  <!-- <span>用户名：{{ item.userName }}</span> -->
                  <div class="userInfo">
                    <div class="head">
                      <span class="el-icon-s-check"></span>
                      <!-- <img src="" alt=""> 如果有用户头像 -->
                    </div>
                    <span>{{item.userName}}</span>
                  </div>
                  <div class="comment_thumbs_up">
                    <span
                      v-show="!item.spot"
                      class="iconfont icon-dianzan"
                      @click="throttleCommentThumbsUpShow(item.commentId, item.spot)"
                    />
                    <span
                      v-show="item.spot"
                      class="iconfont icon-dianzan red"
                      @click="throttleCommentThumbsUpShow(item.commentId, item.spot)"
                    />
                    <i>{{ item.spotNum }}</i>
                  </div>
                </div>
                <div class="comment_info">{{ item.commentContent }}</div>
                <div class="comment_date">{{item.commentDate}}</div>
              </div>
            </li>
          </ul>
          <div class="loadfooter">
            <el-button
              v-if="!noMore"
              :loading="loading"
              type="info"
              style="width:100%;"
              plain
              @click.native.prevent="load"
            >查看更多</el-button>
            <p v-else class="noMoreInfo">没有更多了......</p>
          </div>
        </div>
        <div v-if="!commentFlag" class="noComment">暂无评论......</div>
      </div>
    </div>
  </div>
</template>
<script>
import { mapGetters } from "vuex";
import { Message } from "element-ui";
import Vue from "vue";
import wangeditor from "@/components/Wangeditor";
export default {
  components: {
    wangeditor
  },
  data() {
    return {
      discussId: undefined,
      thumbsUpFlag: false, // 讨论未点赞
      commentThumbsUpFlag: false, // 评论未点赞
      collectionFlag: false, // 未收藏
      thumbsUpNum: 0, // 点赞数量
      collectionNum: 0, // 收藏数量
      commentText: "",
      commentFlag: true,
      isDisabled: false,
      commentLoading: false, //评论按钮
      date: new Date(),
      timer: null,
      timer2: null,
      count: 1, // 起始页数值为1
      limit: 5, // 每页条数
      loading: false,
      totalPages: undefined, // 取后端返回内容的总页数
      total: undefined,
      list: [], // 后端返回的数组

      detail: {},
      visibility: "visible",
      current: ""
    };
  },
  computed: {
    ...mapGetters(["userId", "name"]),
    noMore() {
      // 当起始页数大于总页数时停止加载
      return this.count >= this.totalPages;
    },
    disabled() {
      return this.loading || this.noMore;
    }
  },
  watch: {
    $route: {
      handler() {
        if (this.$route.query.id == "" || this.$route.query.id == null) {
          this.$router.push({ path: "/discuss/index" });
        } else {
          this.discussId = this.$route.query.id;
          this.current = this.$route.query.current;
        }
      },
      deep: true,
      immediate: true
    },
    detail: {
      handler(newDetail) {
        if (newDetail.isComment == "0") {
          this.visibility = "hidden";
        }
        if (newDetail.isComment == "1") {
          this.visibility = "visible";
        }
      },
      deep: true,
      immediate: true
    }
  },

  mounted() {
    this.getMessage();
    this.getDiscussDetail();
    if (window.history && window.history.pushState) {
      // 向历史记录中插入了当前页
      history.pushState(null, null, document.URL);
      window.addEventListener("popstate", this.goBack, false);
    }
  },
  created() {},
  destroyed() {
    window.removeEventListener("popstate", this.goBack, false);
  },
  methods: {
    goBack() {
      console.log("点击了浏览器的返回按钮");
      // window.history.back();
      this.$router.push({
        name: "Discuss",
        query: { current: this.current }
      });
    },
    getDiscussDetail() {
      this.$axios
        .get("forum/view", {
          params: {
            forumId: this.discussId
          }
        })
        .then(res => {
          this.detail = res.data;
          this.thumbsUpFlag = res.data.spot;
        });
    },
    getMessage() {
      const params = {
        current: this.count,
        limit: this.limit, // 每页查询条数
        discussId: this.discussId
      };
      this.$axios.get("/forum/commentList", { params }).then(res => {
        this.list = this.list.concat(res.data.records); // 因为每次后端返回的都是数组，所以这边把数组拼接到一起
        if (this.list.length <= 0) {
          this.commentFlag = false;
        } else {
          this.commentFlag = true;
        }
        this.total = res.data.total;
        this.totalPages = Math.ceil(res.data.total / this.limit);
        this.loading = false;
      });
    },
    throttleThumbsUpShow() {
      clearInterval(this.timer);
      this.timer = setInterval(() => {
        this.thumbsUpShow();
        clearInterval(this.timer);
      }, 500);
    },
    thumbsUpShow() {
      this.thumbsUpFlag = !this.thumbsUpFlag;

      if (this.thumbsUpFlag) {
        // 点赞
        this.$axios
          .get("/forum/spot", {
            params: {
              discussId: this.discussId
            }
          })
          .then(() => {
            this.$set(this.detail, "spotNum", this.detail.spotNum + 1);
          });
      } else {
        // 未点赞
        this.$axios
          .get("/forum/unSpot", {
            params: {
              discussId: this.discussId
            }
          })
          .then(() => {
            this.$set(this.detail, "spotNum", this.detail.spotNum - 1);
          });
      }
    },
    throttleCommentThumbsUpShow(commentId, spot) {
      clearInterval(this.timer2);
      this.timer2 = setInterval(() => {
        this.commentThumbsUpShow(commentId, spot);
        clearInterval(this.timer2);
      }, 500);
    },
    commentThumbsUpShow(commentId, spot) {
      if (!spot) {
        // 点赞
        this.$axios
          .get("/forum/commentSpot", { params: { commentId } })
          .then(res => {
            this.list.forEach(item => {
              if (item.commentId == commentId) {
                item.spot = !spot;
                item.spotNum = res.data.spotNum;
              }
            });
          });
      } else {
        // 取消点赞
        this.$axios
          .get("/forum/commentUnSpot", { params: { commentId } })
          .then(res => {
            this.list.forEach(item => {
              if (item.commentId == commentId) {
                item.spot = !spot;
                item.spotNum = res.data.spotNum;
              }
            });
          });
      }
    },
    collectionShow() {
      this.collectionFlag = !this.collectionFlag;
    },
    commenthandle() {
      this.commentLoading = true;
      if (this.commentText == "") {
        Message.error("评论内容不能为空");
        this.commentLoading = false;
      } else {
        this.$axios
          .post("/forum/comment", {
            userId: this.userId,
            discussId: this.discussId,
            commentContent: this.commentText.trim()
          })
          .then(res => {
            this.commentText = "";
            Message.success("评论成功");
            this.count = 1;
            this.list = [];
            this.commentLoading = false;
            this.getMessage();
          })
          .catch(() => {
            Message.error("评论失败，请检查网络");
          });
      }
    },
    goback() {
      this.$router.push({
        name: "Discuss",
        query: { current: this.current }
      });
    },
    download(id) {
      window.open(`/api/guns/system/download/${id}`, "_self");
    },
    load() {
      // 点击按钮进行加载
      this.loading = true;
      this.count += 1; // 页数+1
      this.getMessage(); // 调用接口，此时页数+1，查询下一页数据
    }
  }
};
</script>
<style lang="scss" scoped>
.detail {
  width: 60%;
  height: 100%;
  margin-left: 20%;
  color: #a7a7a7;
  .red {
    color: red;
  }
  .detailShare {
    padding: 15px;
    border: 1px solid #ccc;
    border-radius: 5px;
  }
  h2 {
    text-align: center;
    color: #000;
  }
  .detailInfo {
    display: flex;
    margin-bottom: 20px;
    .share {
      width: 50%;
    }
    .info_right {
      span {
        float: right;
      }
    }
  }
  .detailConten {
    text-indent: 2em;
    min-height: 200px;
    max-height: 350px;
    margin-bottom: 20px;
    overflow: auto;
    line-height: 24px;
  }
  .interactive {
    margin-bottom: 20px;
    display: flex;
    justify-content: space-between;
    .interactive_left {
      display: flex;
      flex: 1;
      flex-wrap: wrap;
      a {
        color: #5584ff;
        display: inline-block;
        margin-right: 10px;
        font-size: 14px;
        line-height: 18px;
        margin-bottom: 5px;
      }
    }
    .comment_input {
      width: 78%;
    }
    .thumbs_up {
      i {
        margin-left: 6px;
      }
    }
    .collection {
      padding-top: 8px;
      margin-left: 1%;
      position: relative;
      i {
        position: absolute;
        top: 15px;
        right: -12px;
      }
    }

    span {
      font-size: 26px !important;
      cursor: pointer;
    }
    i {
      font-style: normal;
    }
  }

  .comment_total {
    float: right;
  }
  .comment {
    overflow-y: auto;
    margin-bottom: 20px;
    border: none;
    ul {
      margin-bottom: 20px;
      box-sizing: border-box;
      padding-left: 0px;
      // padding: 0 20px;
    }
    li {
      border-bottom: 1px solid #f1f1f1;
      margin-bottom: 15px;
      display: flex;
      box-sizing: border-box;
      padding: 20px 0;
    }
    .logo {
      width: 30px;
      height: 30px;
      border: 1px solid;
      border-radius: 50%;
    }
    .comment_content {
      flex: 1;
      font-size: 14px;
      width: 100%;
      .comment_user {
        display: flex;
        justify-content: space-between;
        height: 32px;
        line-height: 32px;
        margin-bottom: 10px;
        .comment_thumbs_up {
          span {
            font-size: 16px !important;
            cursor: pointer;
          }
          i {
            font-style: normal;
            margin-left: 3px;
          }
        }
      }
      .comment_info {
        box-sizing: border-box;
        word-break: break-all;
        width: 100%;
        padding-left: 45px;
        line-height: 22px;
        // text-indent: 2em;
        margin-bottom: 15px;
      }
      .comment_date {
        padding-left: 45px;
      }
    }
    .loadfooter {
      .noMoreInfo {
        font-size: 14px;
        text-align: center;
      }
    }
    .noComment {
      height: 50px;
      line-height: 50px;
      text-align: center;
      font-size: 14px;
    }
  }
}
.userInfo {
  display: flex;
  font-size: 14px;
  line-height: 35px;
  margin-bottom: 15px;
  .head {
    margin-right: 10px;
    width: 35px;
    height: 35px;
    border-radius: 50%;
    background-color: #efefef;
    text-align: center;
    span {
      font-size: 18px !important;
      color: #d9d9d9;
    }
  }
}
.setHeight {
  margin-bottom: 15px;
  /deep/.el-textarea__inner {
    min-height: 100px !important;
  }
}
.commentBtn {
  display: flex;
  justify-content: space-between;
  height: 36px;
  line-height: 36px;
  margin-bottom: 15px;
  .commentInfo {
    font-size: 14px;
    box-sizing: border-box;
    padding: 0 20px;
    flex: 1;
    display: flex;
    justify-content: space-between;
    color: #ccc;
  }
}
.fixed {
  position: fixed;
  right: 30px;
  top: 75px;
}
</style>
